package cn.hj.domain.activity.service.quota.chain.impl;

import cn.hj.domain.activity.model.entity.ActivityCountEntity;
import cn.hj.domain.activity.model.entity.ActivityEntity;
import cn.hj.domain.activity.model.entity.ActivitySkuEntity;
import cn.hj.domain.activity.model.vo.ActivitySkuStockKeyVO;
import cn.hj.domain.activity.repository.IActivityRepository;
import cn.hj.domain.activity.service.armory.IActivityDispatch;
import cn.hj.types.enums.ResponseCode;
import cn.hj.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 活动sku库存规则节点
 */
@Component("activity_sku_stock_action")
@Slf4j
public class ActivitySkuStockChain extends ActivityBaseActionChain {

    @Resource
    private IActivityRepository activityRepository;

    @Resource
    private IActivityDispatch activityDispatch;

    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityCountEntity activityCountEntity, ActivityEntity activityEntity) {
        log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】开始。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());

        //库存扣减
        boolean status = activityDispatch.subtractionActivitySkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());
        if (status) {
            log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】成功。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());

            activityRepository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder()
                    .sku(activitySkuEntity.getSku())
                    .activityId(activityEntity.getActivityId())
                    .build());
            return true;
        }

        throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());

    }
}
